<template>
	<view>
		<view style="margin-bottom: 100rpx;">
			<view v-for="(item,index) in list" :key="index" >
				
				<view style="font-size: 36rpx;line-height: 36rpx;margin-left: 40rpx;margin-top: 40rpx;">{{index+1}}.{{item.name}}</view>

				<radio-group @change="changeSelectRadio(item.item,index)" v-if="item.type==1">
					<label v-for="(i,ind) in item.item"  @click="addQuest(i,ind,index,item)" :key="ind" class="lable" :name="ind" >
						<view>
							<radio color="#007AFF" />
						</view>
						<view style="margin-left: 20rpx;">{{i.name}}</view>
						
					</label>
					<view v-if="item.showUpload">
						<view style="font-size: 34rpx;line-height: 34rpx;margin-top: 40rpx;margin-left: 30rpx;">可上传照片(1-4张)</view>
						<!-- <view>
							<view style="width: 150rpx;height: 150rpx;background-color: #F5F5F8;margin-top: 30rpx;margin-left: 30rpx;border-radius: 8rpx;" v-if="item.fileList.length==0">
								<image src="../../static/btn_takephoto@3x.png" style="width: 88rpx;height: 88rpx;margin-top: 31rpx;margin-left: 31rpx;" @click="uploadImg(item.fileList,index)" ></image>
							</view>
							<view v-else style="margin-left: 10rpx;">
								<view class="qqq" style="width:150rpx;height: 150rpx ;display: inline-block; position: relative;margin-left: 20rpx;margin-top: 30rpx;" v-for="(item,index) in item.fileList">
									<image  :src="item" style="width: 150rpx;height: 150rpx; position: absolute;border-radius: 8rpx;"></image>
									<view>{{item.url}}</view>
									<image  src="../../static/btn_delete@3x.png" style="position: absolute;width: 40rpx;height: 40rpx;right: -20rpx;top: -20rpx;" @click="deleImg(item,index)"></image>
								</view>	
								<view style="width: 150rpx;height: 150rpx;background-color: #F5F5F8;margin-top: 30rpx;margin-left: 30rpx;border-radius: 8rpx;" v-if="item.fileList.length<4 && item.fileList.length!=0">
									<image src="../../static/btn_takephoto@3x.png" style="width: 88rpx;height: 88rpx;margin-top: 31rpx;margin-left: 31rpx;" @click="uploadImg(item.fileList,index)" ></image>
								</view>	
							</view>	
						</view> -->
					
						<view style="margin-left: 30rpx;margin-top:20rpx;padding-right: 10rpx;">
							<uni-file-picker
								v-model="item.fileList2"  
								file-mediatype="image"
								mode="grid"
								:limit="4"
								@progress="progress" 
								@success="success" 
								@fail="fail" 
								@select="select"
								@delete="deletess($event,index)"
							/>
							<!-- <button @click="go" type="default">上传1</button> -->
						</view>	
					
					</view>
				</radio-group>
				<view v-else-if="item.type==3">
					<view v-if="item.tip" style="width: 88%;margin-left: 36rpx;background-color: rgba(245, 245, 248, 1);margin-top: 20rpx;padding: 20rpx 16rpx;font-size: 32rpx;color: rgba(102, 102, 102, 1);">配备标准：{{item.tip}}</view>
					<textarea v-model="item.checkBox" @input="input(item)" style="margin-left: 36rpx;border: 1rpx solid #d6e4ef;margin-top: 20rpx;padding: 18rpx;font-size: 32rpx;border-radius: 8rpx;line-height: 1.5;"/>
				</view>
				<view style="width: 750rpx;height: 2rpx;background-color: #E5E5E5;margin-top: 66rpx;"></view>
			</view>
		</view>
		<view style="position: fixed;bottom: 0;width: 750rpx;height: 100rpx;box-shadow: 0 0 8rpx 0 rgba(0, 0, 0, 0.2);display: flex;background-color: #FFFFFF;">
			<image src="../../static/btn_thumbnail_pop@3x.png" style="width: 30rpx;height: 30rpx;margin-left: 40rpx;padding-top: 36rpx;"></image>
			<view style="font-size: 28rpx;line-height: 28rpx;margin-left: 10rpx;margin-top: 38rpx;color: #666666;">{{checkedNum}}/{{list.length}}</view>
			<view style="width: 20rpx;height: 20rpx;border-radius: 90rpx;background-color: #FF4D4F; margin-top: 40rpx;margin-left: 80rpx;"></view>
			<view style="font-size: 24rpx;line-height: 24rpx;margin-left: 10rpx;margin-top: 38rpx;color: #666666;">{{troubleNum}}处隐患</view>
			<button style="width: 240rpx;height: 76rpx;position: absolute;right: 20rpx;background-color: rgba(81, 154, 255, 0.3);color: #FFFFFF;border-radius: 36rpx;margin-top: 12rpx;font-size: 36rpx;line-height: 76rpx;" v-if="checkedNum!=list.length">立即提交</button>
			<!-- <button style="width: 240rpx;height: 76rpx;position: absolute;right: 20rpx;background-color: rgba(81, 154, 255, 0.3);color: #FFFFFF;border-radius: 36rpx;margin-top: 12rpx;font-size: 36rpx;line-height: 76rpx;" v-if="checkedNum!=list.length">立即创建</button> -->
			<button style="width: 240rpx;height: 76rpx;position: absolute;right: 20rpx;background-color: #519AFF;color: #FFFFFF;border-radius: 36rpx;margin-top: 12rpx;font-size: 36rpx;line-height: 76rpx;" @click="finish" v-else>立即提交</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				items: [],
				current: '',
				actives:false,
				num:0,
				ownerId:'',
				list:[],
				question:[],
				listOrder:[],
				resQuest:[],
				imgArr:[],
				filelist:[],
				tokenUser:''
			}
		},
		methods: {
			// go(){
			// 	uni.chooseImage({
			// 		count:9,
			// 		sizeType:['original', 'compressed'],
			// 		sourceType: ['album'], //从相册选择
			// 		success:(res)=>{
			// 			console.log(res,'=======');
			// 		}

			// 	})
			// },
			
			select(e){
				console.log(this.$refs.gg,'this.$refs.gg');
				
			    console.log('选择文件：',e)
				// this.list[this.selectQuestIndex].fileList.push(...e.tempFilePaths)
				console.log(e.tempFilePaths,'22222');
				// this.$myRequest({
				// 	url:'/project_flood/v1/public/upload/mark/image',
				// 	data:{e.tempFilePaths}
				// }).then((res)=>{
				// 	console.log(res);
				// })
				console.log(this.list[this.selectQuestIndex].fileList,'*********');
				let filePath = e.tempFilePaths[0]
				console.log(filePath);
				e.tempFilePaths.map(e=>{
					uni.uploadFile({
							 url: 'https://project.develop.lanchengiot.cn/project_flood/v1/public/upload/mark/image', //仅为示例，非真实的接口地址
								filePath: e,
								name: 'file',
								formData: {
									'user': 'test'
								},
								success: (res) => {
									console.log(JSON.parse(res.data).data.url,'8989');
									let url = JSON.parse(res.data).data.url
									 if(this.list[this.selectQuestIndex].fileList2){
											this.list[this.selectQuestIndex].fileList2.push({url:url})
										}else{
											this.$set(this.list[this.selectQuestIndex], 'fileList2', [{ url:url}])
										}
										console.log(this.list[this.selectQuestIndex],'上传的图片');
								}
					})
				})
				
					
			},
			success(e){
			    console.log('上传成功*******',e)
			},
			fail(e){
				console.log('555');
			},
			radioChange(e) {
				console.log(e);
			},
			deletess(e,listindex){
				console.log(e);
				console.log(index);
				let s = this.list[listindex].fileList2.indexOf(e.tempFilePath);
				
				let index = this.list[listindex].fileList2.findIndex(v=>v.url === e.tempFilePath)
				console.log(index,'index------');
				
				
				this.list[listindex].fileList2.splice(index,1)
				
				console.log(s);
				
			},
			active(item,index){
				console.log(item,'2222');
				console.log(index,'1111');
				console.log(item.image,'image');
				// this.list.map(i=>{
				// 	this.$set(i,'ischecked',true)
				// })
				if(item.image==1){
					this.actives=true
				}
				else{
					this.actives=false
				}
			},
			finish(){
				console.log(this.list);
				let questionList = this.list.map(e=>{
					// 其他隐患
					if(e.type === '4'){
						this.list.map(e=>{
							console.log(e,'e')
						})
						return {
							id: e.id,
							label: this.list.map(e=>{
								return {
									images: e.fileList2 ? e.fileList2.map(e=>e.url) : null,
									remark: e.remark +'',
									value: e.value
								}
							})
						}
					}
					return {
						id: e.id,
						images: e.fileList2 ? e.fileList2.map(e=>e.url) : null,
						// index: [e.radio],
						index: [e.item.findIndex(e=>e.isSelected)],
						// itemRemark: e.message || null,   //文本输入
						remark: e.checkBox + '',
						score: e.item.find(e=>e.isSelected) ? e.item.find(e=>e.isSelected).score : 0,
					}
				})
				let data = {
					ownerId: this.ownerId,
					
					type: '2',
					score: 1, //目前写死传0
					question: questionList,
				}
				
				console.log(data,'kkk');
				uni.showToast({
					title:`巡查提交成功！`,
					icon:'none'
				}).then((res)=>{
					setTimeout(()=>{
						uni.navigateBack({
							
						})
					},1000)
					
				})
				uni.request({
					url:'https://project.develop.lanchengiot.cn/project_flood/v1/check/anwser/flood/create',
					data:data,
					header:{"Authorization" : this.tokenUser},
					method:'POST',
				}).then((res)=>{
					console.log('成功');
					})
				
			},
			async getTopic(){
				this.$myRequest({
					url:'/project_flood/v1/check/question/flood/dump1',
					data:{'ownerId':this.ownerId}
				}).then((res)=>{
					console.log('成功');
					
					this.listOrder = res.data.data.list;
					this.resQuest =  res.data.data.question
					this.list = this.listOrder.map(e=>{
						return this.resQuest[e]
					})
					this.list.sort((a, b)=>{
						return a.type - b.type
					})
				})
			},
			changeSelectRadio(radioList, index){
			            console.log('----change')
			            console.log(index,'题目的index')
			            this.$set(this.list[index], 'checkBox', []); // 切换radio选择 去除选中的不合格
			            this.$set(this.list[index], 'fileList', []); // 切换radio选择 去除上传的文件
			
			            this.selectQuestIndex = index;
			            setTimeout(()=>{
			                console.log(radioList,'www')
			                console.log(222)
			                radioList.map(e=>{
			                    //选中了  增加题目
			                    if(e.isSelected){
			                        let arr = [];
			                        if(!e.group || e.group.length === 0) return
			                        arr = e.group.map(v=> this.resQuest[v])
			                        // console.log(arr,'arr')
			                        arr.reverse().map(i=>{
			                            this.list.splice(index+1, 0,i)
			                        })
			                        // this.list.splice(index+1, 0,...arr)
			                        this.list = Array.from(new Set(this.list))   // 点击多次 做去重处理
			                        // console.log(this.list,'list------')
			                    }else{
			                        if(!e.group || e.group.length === 0) return
			                        //删除题目
			                        let arr = [];
			                        arr = e.group.map(e => this.resQuest[e])
			                        console.log(arr,'要删除的题目')
			                        let delIds = [];
			                        delIds = arr.map(e=>e.id)
			                        console.log(delIds,'delIds...')
			                        let delIndex = [];
			                        delIndex = delIds.map(v=>{
			                            return this.list.findIndex(e=>e.id === v)
			                        })
			                        console.log(delIndex,'hhhh')
			
			                        if(delIndex.includes(-1)) return  //存在-1 说明该题目不存在于列表中 不需要删除
			                        delIndex.map(e=>{
			                            this.list.splice(e,1)
			                        })
			                    }
			
			
			                })
			            },0)
			
			        },
					input(item){
						this.$set(item,'isChecked', true)
					},
					addQuest(e,radioIndex,index,item){
						console.log(index,'index===');
					            this.$set(item,'isChecked', true)
					
					            console.log(this.list,'已填')
					            let checked = this.list.filter(e=>e.isChecked)
					            console.log(checked,'checked')
					
					            console.log('-------add')
					            this.selectQuestId = e.id;
					            item.item.forEach(e=>{
					                e.isSelected = false
					            })
					            console.log(item,'题目item--')
					            this.$set(item.item[radioIndex],'isSelected', true)
					            console.log(1111)
					            //index 题目的index
					            console.log(e,'radio信息')
					            console.log(item,'item--')
					            console.log(radioIndex,'radioIndex--')
					
					            this.$set(item,'selectRadioScore',e.score)
					
					            this.$set(item,'showUpload',!!e.image)
					            this.$set(item,'showRemake',!!e.remark)
					
					
					            //有tags 弹出弹框
					            if(e.isSelected && (e.tags && e.tags.length > 0)){
					                item.showDialog = true
					                this.$forceUpdate()
					                this.dialogSelectList = e.tags;
					            }else{
					                item.showDialog = false
					            }
					
					
					            if(!e.group) return
					
					            // console.log(e.group,'e')
					            //添加题目
					            // let arr = [];
					            // arr = e.group.map(e=>{
					            //     return this.resQuest[e]
					            // })
					            // this.list.splice(index+1, 0,...arr)
					            // this.list = Array.from(new Set(this.list))   // 点击多次 做去重处理
					            // console.log(this.list,'list------')
					
					
					
					        },
							deleImg(item,index){
								console.log(item,'e',index)
								this.list[index].fileList.splice(index,1)
								// this.list[detail.name].fileList2.push({url: res.data.url})
								// this.list[detail.name].fileList.splice(detail.index,1)
								// this.list[detail.name].fileList2.splice(detail.index,1)
								
							},
			increase(){
				this.num++
			},
			uploadImg(fileList,index){
				console.log(index,'----');
				console.log(fileList,'fileList');
				let that =this
				uni.chooseImage({
					count:4,
					success(res) {
						
						that.list[index].fileList=res.tempFilePaths;
						console.log(res.tempFilePaths,'res.tempFilePaths');
						console.log(fileList);
						
						// if(that.list[that.selectQuestIndex].fileList.length === 0){
						// 	that.list[that.selectQuestIndex].fileList.push({
						// 		url: res.tempFilePaths[0]
						// 	})
							
						// }else{
						// 	that.list[that.selectQuestIndex].fileList.push
						// }
					}
					
				})
			},
			deletes(index){
				console.log(index);
				this.imgArr.splice(index,1)
			},
			troubleUploadImg(file,itemIndex){
				 const formData = new FormData();
				            // const x = sessionStorage.getItem('x');
				            // const y = sessionStorage.getItem('y');
				            // formData.append("key",file.file.name);
				            formData.append("file",file.file);
				            // formData.append("userId",sessionStorage.getItem('userId'));
				            // formData.append('time',dayjs().format('YYYY-MM-DD HH:mm:ss'))
				            // formData.append('location',`${x},${y}`)
				
				
				            // uploadImg(formData).then(res=>{
				            //     file.status = 'done ';
				            //     file.message = '上传成功';
				            //     if(this.troubleList[itemIndex.name].fileList2){
				            //         this.troubleList[itemIndex.name].fileList2.push({url: res.data.url})
				            //     }else{
				            //         this.$set(this.troubleList[itemIndex.name], 'fileList2', [{url: res.data.url}])
				            //     }
				            //     console.log(this.troubleList,'this.list')
				            // }).catch(()=>{
				            //     file.status = 'failed';
				            //     file.message = '上传失败';
				            // })
			},
			troubleAfterRead(file,itemIndex){
			            console.log(itemIndex,'item---------------------')
			            console.log(file,'files');
			            file.status = 'uploading';
			            file.message = '上传中...';
			            file.status = 'uploading';
			            file.message = '上传中...';
			            console.log(file instanceof Array,'是数组吗')
			            // 一次选多张上传
			            if(file instanceof Array){
			                file.map((file)=>{
			                    this.troubleUploadImg(file, itemIndex,)
			                })
			                return
			            }
			            this.troubleUploadImg(file, itemIndex,)
			        },
		},
		computed:{
			checkedNum(){
			            let checked = this.list.filter(e=>e.isChecked)
			            return checked.length
			},
			troubleNum(){
						let arr = this.list.filter((e)=>{
							return e.selectRadioScore < 0
						})
						return arr.length
			},
		},
		onLoad() {
			
			
			try {
			    const Y = uni.getStorageSync('ownerId');
				this.ownerId=Y
			    if (Y) {
			        // console.log(Y);
			    }
			} catch (e) {
			    // error
			};
			try {
			    const X = uni.getStorageSync('tokenUser');
				this.tokenUser=X
			    if (X) {
			        // console.log(Y);
			    }
			} catch (e) {
			    // error
			};
			this.getTopic();
		}
	}
</script>

<style>
.lable{
	display: flex;
	margin-top: 50rpx;
	margin-left: 40rpx;
}
</style>
